<template>
  <div class="app-container">
    <div class="filter-container">
      <el-row :gutter="0">
        <el-col :xs="24" :sm="18">
          <el-button class="filter-item" @click="refresh()">刷新</el-button>
        </el-col>
        <el-col :xs="24" :sm="6">
          <el-button class="filter-item" @click="importExcel()" icon="el-icon-circle-plus">导入</el-button>
          <el-button class="filter-item" @click="save()">保存</el-button>
        </el-col>
      </el-row>
    </div>
    <el-scrollbar>
      <table class="table">
          <tr>
            <td>班级</td>
            <td v-for="xueke in xuekes">{{xueke.name}}</td>
          </tr>
          <tr v-for="banji in banjis">
            <td>{{banji.name}}</td>
            <td v-for="xueke in xuekes">
              <input type="text" v-model="shoukebiaoTable[banji.id][xueke.id].name"/>
            </td>
          </tr>
        </table>
    </el-scrollbar>
    <el-dialog :title="importDialogTitle" :visible.sync="importDialog" top="1vh" :before-close="importCancel">
      <el-form ref="ref" label-width="200px" class="dialog-body" :style="{height:height+30+'px'}">
        <el-form-item label="授课表导入模板下载" prop="remark">
          <el-button @click="download">导入模板下载</el-button>
        </el-form-item>
        <el-form-item label="授课表导入" prop="remark">
          <el-upload
                name="excel_file"
                :show-file-list="false"
                :before-upload="uploadBefore"
                :action="uploadAction"
                :headers="uploadHeaders"
                :data="uploadData"
                :on-success="uploadSuccess"
                :on-error="uploadError"
              >
                <el-button type="primary">导入</el-button>
              </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="importCancel">关闭</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import screenHeight from '@/utils/screen-height'
import Pagination from '@/components/Pagination'
import { getUserId, getToken } from '@/utils/auth'
import { getTable,save,download } from '@/api/shoukebiao'

export default {
  name: 'Role',
  components: { Pagination },
  data() {
    return {
      height: 680,
      loading: false,
      xuekes:[],
      banjis:[],
      teachers:[],
      shoukebiaos:[],
      shoukebiaoTable:[],
      importDialog: false,
      importDialogTitle: '',
      uploadAction: process.env.VUE_APP_BASE_API + '/base/shoukebiao/import',
      uploadHeaders: { UserId: getUserId(), Token: getToken() },
      uploadData: { user_id: getUserId() }
    }
  },
  created() {
    this.height = screenHeight()
    this.getTable()
  },
  methods: {
    getTable(){
      this.loading = true
      getTable().then(res => {
        this.xuekes = res.data.xuekes
        this.banjis = res.data.banjis
        this.shoukebiaos = res.data.shoukebiaos
        this.teachers = res.data.teachers
        this.banjis.forEach(banji => {
          this.shoukebiaoTable[banji.id] = new Array(); //  v-model="this.shoukebiaoTable[banji.id][xueke.id].name"
          this.xuekes.forEach(xueke=>{
            var shokebiao = this.shoukebiaos.find(function(elem){return elem.banji_id ==  banji.id && elem.xueke_id == xueke.id});
            if(shokebiao !=undefined){
              var teacher = this.teachers.find(function(elem){return elem.id == shokebiao.teacher_id;});
              this.shoukebiaoTable[banji.id][xueke.id]=JSON.parse(JSON.stringify(teacher))
            }
            else
              this.shoukebiaoTable[banji.id][xueke.id]={id:0,name:''}
          })
        });
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    save(){
      this.loading = true
      let shoukebiaosSave=new Array();
      this.banjis.forEach(banji => {
        this.xuekes.forEach(xueke=>{
          var teacherName = this.shoukebiaoTable[banji.id][xueke.id].name
          var teacher = this.teachers.find(function(elem){return elem.name == teacherName && elem.name !='';});
          if(teacher) {
            shoukebiaosSave.push({banji_id:banji.id,xueke_id:xueke.id,teacher_id:teacher.id});
          }
        })
      });
      //console.log(shoukebiaosSave)
      save(shoukebiaosSave).then(res => {
        this.$message.success(res.msg)
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },
    // 刷新
    refresh() {
      this.getTable()
    },
    importExcel() {
        this.importDialog = true
        this.importDialogTitle = '导入'
      },
      uploadBefore(file) {
        this.loading = true
      },
      uploadSuccess(res, file) {
        if (res.code === 200) {
          this.loading = false
          this.$message.success(res.msg)
          this.importDialog = false
          this.getTable()
        } else {
          this.loading = false
          this.$message.error(res.msg)
        }
      },
      uploadError(error) {
        this.loading = false
        console.log(error)
      },
      importCancel(){
        this.importDialog = false
      },
      download()
      {
        download().then(response => {
          this.downloadFile(response);
          this.$message.success(response.msg)
        }).catch(function (error) {
          console.log(error);
        });
      },
      // 下载文件
      downloadFile (data) {
        if (!data) {
          return
        }
        let blob = new Blob([data])
        let fileName = '授课表导入模板.xlsx'
        if ('download' in document.createElement('a')) { // 不是IE浏览器
          let url = window.URL.createObjectURL(blob)
          let link = document.createElement('a')
          link.style.display = 'none'
          link.href = url
          link.setAttribute('download', fileName)
          document.body.appendChild(link)
          link.click()
          document.body.removeChild(link) // 下载完成移除元素
          window.URL.revokeObjectURL(url) // 释放掉blob对象
        } else { // IE 10+
          window.navigator.msSaveBlob(blob, fileName)
        }
      }
  }
}
</script>

<style scoped>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
table
{
    border-collapse: collapse;
    margin: 0 auto;
    text-align: center;
}
table td, table th
{
    border: 1px solid #cad9ea;
    color: #666;
    height: 30px;
}
table thead th
{
    background-color: #CCE8EB;
    width: 100px;
}
table tr:nth-child(odd)
{
    background: #fff;
}
table tr:nth-child(even)
{
    background: #F5FAFA;
}

input{
    outline-style: none ;
    border: 0px;
    width:70px;
}
</style>


